package com.yuyue.dronesystem.utils;

import java.util.Map;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * myTool
 */
public class myTool {

    Logger logger = LoggerFactory.getLogger(getClass());
    ObjectMapper objectmapper = new ObjectMapper();

     /**
     * 将对象转成json字符串
     * @param object 被转的对象
     * @return 返回json字符串
     */
    public String objToJson(Object object) {
        try {
            return objectmapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            logger.error("对象转json失败", e);
        }
        return null;
    }

    /**
     * 将json字符串转成对象
     * @param <T> 泛型
     * @param jsonString 被转的json字符串
     * @param objectClass 转换后对象的class
     * @return 返回对象
     */
    public <T> T jsonToObject(String jsonString, Class<T> objectClass) {
        try {
            return objectmapper.readValue(jsonString, objectClass);
        } catch (Exception e) {
            logger.error("json转对象失败", e);
        }
        return null;
    }

    /**
     * 将json字符串转成map
     * @param jsonString 被转的json字符串
     * @return 返回map
     */
    @SuppressWarnings("unchecked")
    public Map<String, Object> jsonToMap(String jsonString) {
        try {
            return objectmapper.readValue(jsonString, Map.class);
        } catch (Exception e) {
            logger.error("json转map失败", e);
        }
        return null;
    }
}